from typing import List
from fastapi import APIRouter, HTTPException, Depends, UploadFile, File, Form
from fastapi.responses import StreamingResponse
import io

from api.models.request import ConvertRequest, FileConvertRequest, BatchConvertRequest, ConversionOptions
from api.models.response import ConvertResponse, BatchConvertResponse, ErrorResponse
from shared.conversion import ConversionService
from shared.storage import StorageManager
from shared.config import settings

router = APIRouter()

# 创建存储管理器和转换服务
storage_manager = StorageManager(settings.storage_path, settings.file_ttl)
conversion_service = ConversionService(storage_manager)


@router.post("/convert", response_model=ConvertResponse)
async def convert_markdown(request: ConvertRequest):
    """转换 Markdown 内容为 PowerPoint"""
    try:
        result = await conversion_service.convert_content(
            request.markdown_content,
            request.options,
            request.output_filename
        )
        
        return ConvertResponse(
            success=True,
            message="Conversion completed successfully",
            data=result
        )
    
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")


@router.post("/convert/upload", response_model=ConvertResponse)
async def convert_upload(
    markdown_file: UploadFile = File(...),
    theme: str = Form(default=settings.default_theme),
    output_filename: str = Form(default=None),
    image_width_ratio: float = Form(default=settings.default_image_width_ratio)
):
    """上传 Markdown 文件并转换为 PowerPoint"""
    
    # 验证文件类型
    if not markdown_file.filename.endswith('.md'):
        raise HTTPException(status_code=400, detail="Only .md files are supported")
    
    # 验证文件大小
    content = await markdown_file.read()
    if len(content) > settings.max_file_size:
        raise HTTPException(status_code=400, detail="File too large")
    
    try:
        # 创建转换选项
        options = ConversionOptions(
            theme=theme,
            image_width_ratio=image_width_ratio
        )
        
        # 转换内容
        markdown_content = content.decode('utf-8')
        result = await conversion_service.convert_content(
            markdown_content,
            options,
            output_filename or markdown_file.filename.replace('.md', '.pptx')
        )
        
        return ConvertResponse(
            success=True,
            message="File converted successfully",
            data=result
        )
    
    except UnicodeDecodeError:
        raise HTTPException(status_code=400, detail="File must be UTF-8 encoded")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")


@router.post("/convert/batch", response_model=BatchConvertResponse)
async def convert_batch(request: BatchConvertRequest):
    """批量转换 Markdown 内容"""
    try:
        results = []
        
        for convert_req in request.files:
            result = await conversion_service.convert_content(
                convert_req.markdown_content,
                convert_req.options,
                convert_req.output_filename
            )
            results.append(result)
        
        return BatchConvertResponse(
            success=True,
            message=f"Successfully converted {len(results)} files",
            data=results
        )
    
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Batch conversion failed: {str(e)}")


@router.get("/files/{file_id}")
async def download_file(file_id: str):
    """下载转换后的文件"""
    try:
        file_data = await conversion_service.get_file(file_id)
        if not file_data:
            raise HTTPException(status_code=404, detail="File not found or expired")
        
        content, metadata = file_data
        
        return StreamingResponse(
            io.BytesIO(content),
            media_type=metadata.get("content_type", "application/octet-stream"),
            headers={
                "Content-Disposition": f"attachment; filename={metadata['filename']}"
            }
        )
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Download failed: {str(e)}")


@router.delete("/files/{file_id}")
async def delete_file(file_id: str):
    """删除文件"""
    try:
        success = await storage_manager.delete_file(file_id)
        if not success:
            raise HTTPException(status_code=404, detail="File not found")
        
        return {"success": True, "message": "File deleted successfully"}
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Delete failed: {str(e)}")


@router.get("/cleanup")
async def cleanup_expired():
    """清理过期文件"""
    try:
        count = await conversion_service.cleanup_expired_files()
        return {
            "success": True,
            "message": f"Cleaned up {count} expired files"
        }
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Cleanup failed: {str(e)}")


@router.get("/themes")
async def get_supported_themes():
    """获取支持的主题列表"""
    return {
        "themes": settings.supported_themes,
        "default_theme": settings.default_theme
    }